package panel;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import util.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;

public class CreateAdapterPanel extends JPanel {
    private Project project;
    private AnActionEvent event;
    private CloseListener closeListener;

    private JTextField adapterName, author, dataFullPath, description;
    private JComboBox<String> typeBox;

    /*当前右键选中包 com.aa.aa */
    private String packagebase = "";
    /**
     * 右键路径
     **/
    private String rightClickPath = "";
    private String appId = "";

    public CreateAdapterPanel(AnActionEvent event, CloseListener closeListener) {
        this.event = event;
        this.closeListener = closeListener;
        initDir();
        initView();
    }

    private void initDir() {
        project = event.getData(PlatformDataKeys.PROJECT);
        packagebase = PathUtil.readPackageName(event);
        rightClickPath = PathUtil.getFileSavePath(event) + "/";
        appId = PathUtil.readModuleApplicationId(rightClickPath);
    }

    private void initView() {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 2));
        panel.setBorder(BorderFactory.createTitledBorder("命名和类型选择"));

        adapterName = new JTextField("adapter名称");

        panel.add(adapterName);

        author = new JTextField("作者");
        panel.add(author);

        description = new JTextField("adapter描述");
        panel.add(description);

        JPanel type = new JPanel();
        type.setLayout(new FlowLayout());
        type.add(new JLabel("类型"));
        typeBox = new JComboBox();
        typeBox.addItem("通用adapter");
        typeBox.addItem("可左滑的adapter");
        type.add(typeBox);
        panel.add(type);

        add(panel);

        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayout(1, 1));
        panel1.setBorder(BorderFactory.createTitledBorder("数据源指定"));
        dataFullPath = new JTextField("数据源完整路径");
        panel1.add(dataFullPath);
        add(panel1);


        JPanel menu = new JPanel();
        menu.setLayout(new FlowLayout());
        Button cancle = new Button();
        cancle.setLabel("取消");
        cancle.addActionListener(actionListener);
        Button ok = new Button();
        ok.setLabel("确定");
        ok.addActionListener(actionListener);
        menu.add(cancle);
        menu.add(ok);

        add(menu);
    }

    private String dealAppId(String content) {
        content = content.replace("$appId", appId);
        return content;
    }

    private String dealPackageName(String content) {
        content = content.replace("$packageName", packagebase);
        return content;
    }

    private String dealName(String content) {
        content = content.replace("$name", adapterName.getText());
        return content;
    }

    private String dealLayoutName(String content) {
        String layoutName = StringUtil.upperCharToUnderLine(adapterName.getText()) + "_item";
        content = content.replace("$layoutName", layoutName);
        return content;
    }

    private String dealBean(String content) {
        String beanFull = dataFullPath.getText();
        content = content.replace("$beanName", beanFull);
        String[] array = beanFull.split("\\.");
        content = content.replace("$bean", array[array.length - 1]);
        return content;
    }

    /**
     * 1.通用流程,处理顶部注释
     *
     * @param content
     */
    private String dealFileTitle(String content) {
        content = content.replace("$author", author.getText());
        content = content.replace("$date", DateUtil.getNowDateShort());
        content = content.replace("$description", description.getText());
        return content;
    }

    /**
     * 开始生成代码
     */
    private void startInit() {
        String content;
        if (typeBox.getSelectedIndex() == 0) {
            content = readFile(Constants.TemplateRecyclerAdapter, "TemplateRecyclerAdapter.txt");
        } else {
            content = readFile(Constants.TemplateSwipeRecyclerAdapter, "TemplateSwipeRecyclerAdapter.txt");
        }
        content = dealPackageName(content);
        content = dealAppId(content);
        content = dealFileTitle(content);
        content = dealName(content);
        content = dealBean(content);
        content = dealLayoutName(content);
        content = dealSwipeLayoutId(content);
        FileUtils.reWriteFile(content, rightClickPath, adapterName.getText() + ".kt");
        createLayout();
        // 自动刷新目录
        PathUtil.refreshProject(event);
        Messages.showInfoMessage(project, "代码生成成功", "提示");
    }

    private String dealSwipeLayoutId(String content) {
        content = content.replace("$swipeId", "swipe_" + StringUtil.upperCharToUnderLine(adapterName.getText()));
        return content;
    }

    /**
     * 新建layout
     */
    private void createLayout() {
        int position = typeBox.getSelectedIndex();
        String layoutName;
        if (position == 0) {
            layoutName = "recycler_item_layout";
        } else {
            layoutName = "swipe_recycler_item_layout";
        }
        int begin = rightClickPath.indexOf("/src/main/java");
        String layoutPath = rightClickPath.substring(0, begin) + "/src/main/res/layout";
        String layoutContent = readFile(Constants.get(layoutName), "layoutName" + ".txt");
        layoutContent = dealAppId(layoutContent);
        layoutContent = dealSwipeLayoutId(layoutContent);
        String newLayoutName = StringUtil.upperCharToUnderLine(adapterName.getText()) + "_item";
        FileUtils.reWriteFile(layoutContent, layoutPath, newLayoutName + ".xml");
    }

    private String readFile(String fileUrl, String filename) {
        String result = HttpUtil.readRemoteFile(fileUrl);
        if (result == null) {
            InputStream in = null;
            in = this.getClass().getResourceAsStream("../Template/adapter/" + filename);
            String content = "";
            try {
                content = new String(FileUtils.readStream(in), "utf-8");
            } catch (Exception e) {
            }
            return content;
        } else {
            return result;
        }

    }

    private ActionListener actionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("取消")) {
                closeListener.onClose();
            } else {
                closeListener.onClose();
                startInit();
            }
        }
    };
}
